/*
 * IR.h
 */
#ifndef IR_H
#define IR_H

#include <stdio.h>
#include <string.h>
#include <wiringPi.h>

#define PIN_IR 4

char IR_code[4];

void IR_Setup(void)
{
	pinMode(PIN_IR, INPUT);
}

char IR_ReadByte(void)
{
	char byte=0x00;
	for(int i=0; i<8; ++i)
	{
		while(digitalRead(PIN_IR)==1); 
		while(digitalRead(PIN_IR)==0); //0.56ms
		delayMicroseconds(600); //0.56~1.69ms
		byte |= (digitalRead(PIN_IR)<<i); //低位在前
	}
	return byte;
}

char IR_ReadData(void)
{
	memset(IR_code,0,4*sizeof(char));
	char byte={0};
	while(digitalRead(PIN_IR)==1); //空闲状态为高电平
	//引导码
	while(digitalRead(PIN_IR)==0); //9ms
	delayMicroseconds(3000); //2.5ms高电平 
	if(digitalRead(PIN_IR)==0) //判断是否为连续按
	{return 0;}
	while(digitalRead(PIN_IR)==1); //4.5ms
	for(int i=0; i<4; ++i){ //4字节:用户码*2,按键码*2
		byte = IR_ReadByte();
		memcpy(&IR_code[i],&byte,sizeof(char));
	}
	if((IR_code[0]^IR_code[1])==0xff && (IR_code[0]^IR_code[1])==0xff)
	return 1;
	else
	return 0;
}

#endif
